package top.kaoshanji.ch12;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.ch12.synch.Bank;

/**
 * 代码清单 ch12-03：使用同步实现转账(12.4.4节、条件对象)
 * author kaoshanji
 * ^_^
 * create time 2024/11/29 11:34
 */
public class SynchBankTest {

    private static final Logger logger = LogManager.getLogger(SynchBankTest.class);

    public static final int NACCOUNTS = 100;
    public static final double INITIAL_BALANCE = 1000;
    public static final double MAX_AMOUNT = 1000;
    public static final int DELAY = 10;

    public static void main(String[] args) {
        logger.info("...代码清单 ch12-03：使用同步实现转账(12.4.4节、条件对象)...");

        var bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
        for (int i = 0; i < NACCOUNTS; i++) {
            // 来源账户
            int fromAccount = i;
            Runnable r = () -> {
                try {
                    while (true) {
                        // 目标账户
                        int toAccount = (int) (bank.size() * Math.random());
                        double amount = MAX_AMOUNT * Math.random();
                        bank.transfer(fromAccount, toAccount, amount);
                        Thread.sleep((int)(DELAY * Math.random()));
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            };


            var t = new Thread(r);
            t.start();

        }
    }
}
